package ui;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import util.CapsJdbc;
import util.CapsRes;
import util.CapsTableView;

import java.net.URL;
import java.util.*;

public class LesRoomMgr implements Initializable {

   @FXML
   private TextField lno;

   @FXML
   private TextField rno;

   @FXML
   private TextField cls_datetime;
   
   @FXML
   private TextField lesroomCond;

   @FXML
   private TableView<Map<String,String>> lesroomTv;

   @FXML
   private void saveLesRoom(ActionEvent event) {
      List<Object> params = new ArrayList<>(Arrays.asList(rno.getText(),cls_datetime.getText(),lno.getText()));
      String updSql = "update lesson_room_rel set rno=?,cls_datetime=? where lno=?";
      CapsRes capsRes = CapsJdbc.execSQL(updSql,params);
      if (capsRes.getTtlNum() < 1) {
         String addSql = "insert into lesson_room_rel(rno,cls_datetime,lno) values(?,?,?)";
         CapsJdbc.execSQL(addSql,params);
      }
      this.dealQry(null);
   }

   @FXML
   private void qryBylesroom(ActionEvent event) {
      this.dealQry(lesroomCond.getText());
   }

   @Override
   public void initialize(URL url, ResourceBundle rb) {
//	   String strSQL = "select lno,rno,cls_datetime from lesson_room_rel";
//      CapsRes capsRes = CapsJdbc.execSQL(strSQL,null);
//      CapsTableView.dealTableView(capsRes,lesroomTv);
//      CapsTableView.addButtonToTable(lesroomTv,(recMap,idCol) -> {
//    	  String delSql = "delete from lesson_room_rel where lno = ?";
//         List<Object> params = new ArrayList<>(2);
//         params.add(recMap.get("LNO"));
//         CapsJdbc.execSQL(delSql,params);
//      },(recMap,idCol) -> {
//           lno.setText(recMap.get("LNO"));
//           rno.setText(recMap.get("TNO"));
//           cls_datetime.setText(recMap.get("CLS_DATETIME"));
//      });
	   this.dealQry(null);
   }
   
   private void dealQry(String lesroomName) {
	   lesroomTv.setItems(null);
	   lesroomTv.getColumns().clear();
	   String strSQL = "select lno,rno,cls_datetime from lesson_room_rel";
	      List<Object> params = null;
	      if (null != lesroomName && lesroomName.length() > 0) {
	         strSQL += " where lno like ?";
	         params = new ArrayList<>(1);
	         params.add(lesroomName+"%");
	      }
	      CapsRes capsRes = CapsJdbc.execSQL(strSQL,params);
	      CapsTableView.dealTableView(capsRes,lesroomTv);
	      CapsTableView.addButtonToTable(lesroomTv,(recMap,idCol) -> {
	    	  String delSql = "delete from lesson_room_rel where lno = ?";
	         List<Object> delParams = new ArrayList<>(1);
	         delParams.add(recMap.get("lno"));
	         CapsJdbc.execSQL(delSql,delParams);
	         this.dealQry(null);
	      },(recMap,idCol) -> {
	    	  lno.setText(recMap.get("lno"));
	           rno.setText(recMap.get("rno"));
	           cls_datetime.setText(recMap.get("cls_datetime"));
	      });
	   }
}
